<?php
namespace app\flash\controller;
use think\Controller;
use think\Db;
use redis\RedisPackage;
use think\Validate;

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: *");
header('Access-Control-Allow-Methods: POST,GET');
header('Access-Control-Allow-Origin: *');
//header('Access-Control-Allow-Origin: http://localhost:8080/');
header("Access-Control-Allow-Headers: token,Origin, X-Requested-With, Content-Type, Accept");
header("Access-Control-Allow-Headers: *");
header('Access-Control-Allow-Methods: POST,GET，OPTIONS');
//header('Access-Control-Allow-Credential:true');//表示是否允许发送Cookie
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit();
}
class User extends Base {

    public function __construct()
    {
        parent::__construct(); // TODO: Change the autogenerated stub
        $this->user;
    }
    /**
     * 功能：修改用户信息
     * 时间：2019/08/14
     * 作者：张仕虎
     */
    public function saveuser(){
        // phpinfo();die;
        if (Request()->isPost()) {
            // $base = new Base();
            $user_id     = input('id');
            $username    = input('username');
            $usedphone   = input('usedphone');
            $phone       = input('phone');
            $password    = input('password');
            $newpassword = input('newpassword');
            $code        = input('code');
            RedisPackage::getInstance();
            if (empty($user_id)) {
                return json(msg(0,'','用户信息不存在'));
            }
            $res = Db::table('user')->where('id',$user_id)->find();
            if (empty($res)) {
                return json(msg(0,'','未找到此用户'));
            }
            $result ='';
            if ($username) {
               $result = Db::table('user')->where('id',$user_id)->update(['username'=>$username]);
               if ($result) {
                   return json(msg(1,'','修改名称成功'));
               }else{
                   return json(msg(0,'','修改名称失败'));
               }
            }
            if ($phone && $usedphone) {
                $wherephone = \decrypt($usedphone);
                $key = 'updatephone'.$phone;
                $phonecode = RedisPackage::get($key);
                $truephone = Db::table('user')->where('phone',$phone)->find();
                if ($truephone) {
                    return json(msg(0,'','此号码已经注册'));
                }
                if (!empty($code) && $code==$phonecode) {
                    $result = Db::table('user')->where(['id'=>$user_id,'phone'=>$wherephone])->update(['phone'=>$phone]);
                    if ($result) {
                        return json(msg(1,'','修改手机号成功'));
                    }else{
                        return json(msg(0,'','修改手机号失败'));
                    }
                }else{
                    return json(msg(0,'','验证码错误'));
                }  
            }
            if ($password && $phone) {
                $key = 'updatepwd'.$phone;
                $pwdcode = RedisPackage::get($key);
                if (empty($code) || $code != $pwdcode) {
                    return json(msg(0,'','状态码错误'));
                }
                if ($password!=$newpassword) {
                    return json(msg(0,'','新密码必须和确认密码一致'));
                }
                $passwords = md5($password);
                $res = Db::table('user')->where('id',$user_id)->field('password')->find();
                if ($res['password']==$passwords) {
                    return json(msg(0,'','新密码不能和上次密码一致'));
                } 
                $result  = Db::table('user')->where('id',$user_id)->update(['password'=>$passwords]);
                if ($result) {
                    return json(msg(1,'','修改密码成功'));
                }else{
                    return json(msg(0,'','修改密码失败'));
                }
            }
        }else{
            return json(msg(0,'','请求方式错误'));
        }
        
    }
    /**
     * 修改手机号第一次验证码的校验
     * 
     */
    public function upphone(){
        $phone = input('phone');
        $code  = input('code');
        RedisPackage::getInstance();
        $key = 'upphone'.$phone;
        $pwdcode = RedisPackage::get($key);
        if (empty($code) || $code !=$pwdcode) {
            return json(msg(0,'','验证码错误'));
        }else{
            $data= \encrypt($phone);
            return json(msg(1,$data,'验证码正确'));
        }
    }
   /**
    * 登录查询个人信息 
    *
    */
    public function usermessage(){
        $data = $this->user;
        $password = Db::table('user')->where('id',$data['id'])->field('password')->find();
        if ($password['password']) {
            unset($password['password']);
            $data['pwdstatus'] = 1;
        }else{
            unset($password['password']);
            $data['pwdstatus'] =2;
        }
        if (empty($data['username'])) {
            $data['username'] = $data['phone'];
        }
        RedisPackage::getInstance();
        $key = 'ht_'.$data['id'];
        $token = RedisPackage::get($key);
        return json(msg(1,['res'=>$data,'token'=>$token],'查询成功'));
    }
    /**
     * 头像上传
     * 
     * 
     */
    public function avatarupload(){
        $upload = new Upload();
        $res = $upload->upload2();
        $res = json_decode($res,true);
        if($res['status']==0){
            return json(msg(0,'',$res['msg']));
        }else{
            $url = $res['data']['src'];
            $id = $this->user['id'];
            $up = db('user')->where(array('id'=>$id))->update(array('picture'=>$url));
            if($up){
                return json(msg(1,$url,'上传成功'));
            }else{
                return json(msg(1,$url,'上传失败'));
            }
        }
    }

    //查询评论我的
    public function comment_me(){
        $user = $this->user;
        //修改是否已读
        db('reply')
            ->alias('r')
            ->where([
                ['to_id','eq',$user['id']],
                ['r.from_id','neq',$user['id']],
                ['r.is_du','eq',0]
            ])
            ->update(array('is_du'=>1));
        $res = db('reply')
            ->alias('r')
            ->join('user u','u.id = r.from_id','left')
            ->join('comment c','r.cid = c.id','left')
            ->where([
                ['to_id','eq',$user['id']],
                ['r.from_id','neq',$user['id']],
            ])
            ->field('r.id,r.from_id,r.content,u.username,u.phone,u.picture,r.create_time,r.parent_id,r.cid,r.to_id,r.is_du,c.flag,c.message_id')
            ->order('create_time desc')
            ->paginate(20,false,['query'=>request()->param()])
            ->each(function ($item,$key){
                $item['content'] = json_decode($item['content']);
                if($item['flag']==1){
                    $tableName = 'flashs';
                }elseif($item['flag']==2){
                    $tableName = 'deepness';
                }else{
                    $tableName = 'friend_message';
                }
                if (empty($item['username'])) {
                    $item['username'] = $item['phone'];
                }
                $item['title'] = Db::table($tableName)->where('id',$item['message_id'])->value('title');
                return $item;
            });
        return json(msg(0,$res,'评论我的查询成功'));
    }

    //评论我的详情
    public function comment_me_detail(){
        $data = input('');
        $validate = Validate::make([
            'id'  => 'require',
        ]);
        $res = $validate->check($data);
        if($res !== true){
            return json(msg(0, '', $validate->getError()));
        }
        //回复内容
        $reply = db('reply r')
            ->join('user u','u.id = r.from_id','left')
            ->field('r.id,u.username,u.picture,r.content,r.parent_id,r.cid,r.create_time')
            ->where('r.id',$data['id'])
            ->find();
        $reply['content'] = json_decode($reply['content']);
        if(count($reply)>0){
            //回复的上级内容
            if($reply['parent_id']==0){
                $parent =  db('comment')
                    ->alias('c')
                    ->join('user u','u.id = c.from_id','left')
                    ->field('c.id,u.username,u.picture,c.content,c.create_time')
                    ->where('c.id',$reply['cid'])
                    ->find();
            }else{
                $parent =  db('reply')
                    ->alias('r')
                    ->join('user u','u.id = r.from_id','left')
                    ->field('r.id,u.username,u.picture,r.content,r.create_time')
                    ->where('r.id',$reply['parent_id'])
                    ->find();
            }
            $parent['content'] = json_decode($parent['content']);
        }else{
            return json(msg(0, compact('reply','parent'), 'ID不合法'));
        }

        return json(msg(1, compact('reply','parent'), '评论详情返回成功'));
        //该顶级评论下的所有回复

    }

    //最新评论我的数量
    public function xiaoxi_new(){
        $user = $this->user;
        //评论我的
        $comment_me_count = db('reply')
            ->alias('r')
            ->where([
                ['to_id','eq',$user['id']],
                ['r.from_id','neq',$user['id']],
                ['r.is_du','eq',0]
            ])->count('r.id');
        //赞我的
        $zan_me_count = db('like_all')
            ->alias('l')
            ->where([
                ['to_id','eq',$user['id']],
                ['user_id','neq',$user['id']],
                ['l.is_du','eq',0]
            ])->count('l.id');
        //关注我的
        $guanzhu_me = db('follow')
            ->alias('f')
            ->where([
                ['followid','eq',$user['id']],
                ['userid','neq',$user['id']],
                ['is_follw','eq',1],
                ['f.is_du','eq',0]
            ])->count('f.id');
        return json(msg(1,compact('comment_me_count','zan_me_count','guanzhu_me'),'评论我的最新数量'));
    }

       //关注我得
    public function attentionme(){
         $userid = $this->user['id'];
        //修改是否已读
        db('follow')
            ->alias('f')
            ->where([
                ['followid','eq',$userid],
                ['userid','neq',$userid],
                ['is_follw','eq',1],
                ['is_du','eq',0]
            ])
            ->update(array('is_du'=>1));
        $res = Db::table('follow')->where(['followid'=>$userid,'is_follw'=>1])->field('userid,followtime')->select();
        $data = [];
        foreach ($res as $key => $v) {
            $data = Db::table('user')->where(['id'=>$v['userid']])->field('username,phone,picture,rand_id')->find();
            if (empty($data['username'])) {
                $data['username'] = $data['phone'];
            }
            $res[$key]['creat_time'] = date('Y-m-d H:i:s',$v['followtime']);
            $res[$key]['username'] = $data['username'];
            $res[$key]['picture'] = $data['picture'];
            $res[$key]['rand_id'] = $data['rand_id'];
            unset($res[$key]['followtime']);
        }
        return json(msg(1,$res,'查询成功'));
    }

    //评论点赞
    public function like(){
        $id         = input('id');//评论ID
        $like_count = input('like_count');//评论状态 1-点赞 2-取消点赞
        $type = input('type');//1:评论2.回复
        //$user_id    = input('user_id');//用户id
        $user_id    = $this->user['id'];
        $create_time= strtotime(date('Y-m-d H:i:s'));//创建时间
        if (empty($id)) {
            return json(msg(0,'','id未找到!'));
        }
        if($type==1){
            $tableName = 'comment';
        }else{
            $tableName = 'reply';
        }
        if ($like_count==1) {
            if ($user_id) {
                //查询是否点赞
                $select = Db::table('like_all')->where(array( 'user_id' => $user_id, 'comment_id'=> $id, 'type'=>$type))
                    ->find();
                if($select){
                    return json(msg(0,'','您已点赞，不可重复点'));
                }
                $arr = array(
                    'user_id'   => $user_id,
                    'comment_id'=> $id,
                    'create_time' => $create_time,
                    'type'=>$type,
                );
                $arr['to_id'] = Db::table($tableName)->where('id',$id)->value('from_id');
                if($type==1){
                    //查询被点赞人id
                    $comment = Db::table('comment')
                        ->field('message_id,flag')
                        ->where(array('id'=>$id))
                        ->find();
                    $arr['message_id'] = $comment['message_id'];
                    $arr['flag'] = $comment['flag'];
                }else{
                    $reply = Db::table('reply')
                        ->alias('r')
                        ->join('comment c','r.cid=c.id')
                        ->field('c.message_id,c.flag')
                        ->where(array('r.id'=>$id))
                        ->find();
                    $arr['message_id'] = $reply['message_id'];
                    $arr['flag'] = $reply['flag'];
                }
                $result = Db::table('like_all')->insert($arr);
                if (!$result) {
                    return json(msg(0,'','点赞失败'));
                }
            }
            $res = Db::table($tableName)->where(['id'=>$id])->setInc('like_count');
            if ($res) {
                return json(msg(1,'','成功'));
            }else{
                return json(msg(0,'','失败'));
            }
        }else{
            $find = Db::table($tableName)->where(['id'=>$id])->find();
            if ($find['like_count']==0) {
                return json(msg(0,'','不能再点了！'));
            }
            $res = Db::table($tableName)->where(['id'=>$id])->setDec('like_count');
            if ($user_id) {
                $find = Db::table('like_all')
                    ->where(array( 'user_id'=> $user_id,
                        'comment_id'=> $id))->find();
                if(!$find){
                    return json(msg(0,'','未找到您的点赞'));
                }
                $res = Db::table('like_all')->where(['comment_id'=>$id,'user_id'=>$user_id])->delete();
            }
            if ($res) {
                return json(msg(1,'','成功'));
            }else{
                return json(msg(0,'','失败'));
            }
        }

    }

    //赞我的人
    public function zan_me(){
        $user = $this->user;
        db('like_all')
            ->alias('r')
            ->where([
                ['to_id','eq',$user['id']],
                ['user_id','neq',$user['id']],
                ['is_du','eq',0]
            ])->update(array('is_du'=>1));
        $res = db('like_all')
            ->alias('l')
            ->join('user u','u.id = l.user_id','left')
            ->where([
                ['to_id','eq',$user['id']],
                ['user_id','neq',$user['id']],
            ])
            ->field('l.id,l.comment_id,l.create_time,l.type,l.message_id,l.flag,u.username,u.phone,u.picture')
            ->order('create_time desc')
            ->paginate(20,false,['query'=>request()->param()])->each(function ($item,$key){
                $item['create_time'] = date('Y-m-d H:i:s',$item['create_time']);
                if($item['flag']=1){
                    $tableName = 'flashs';
                }elseif($item['flag']=2){
                    $tableName = 'deepness';
                }elseif($item['flag']=3){
                    $tableName = 'friend_message';
                }
                if (empty($item['username'])) {
                    $item['username'] = $item['phone'];
                }
                $message = Db::table($tableName)->where('id',$item['message_id'])->find();
                if(count($message)>0){
                    $item['title'] = $message['title'];
                }
                return $item;
            });
        return json(msg(0,$res,'赞过我的查询成功'));
    }

    /**
     * 查询评论的最新数据
     *
     */
    public function poll(){
        $user = $this->user;
        $id = input('id');
        if (empty($id)) {
            return json(msg(0,'','参数错误'));
        }
        $data = Db::query("select * from reply where id>$id and to_id=".$user['id']);
        $count = count($data);
        return json(msg(1,$count,'最新评论数量返回成功'));
    }



}